


var EXPORTED_SYMBOLS = ["CommandLineHandler"];


let CommandLineHandler = (function() {
    "use strict";
    const Cu = Components.utils;
    const Ci = Components.interfaces;
    const Cc = Components.classes;
    const Cr = Components.results;
    function require(url) {
        let scope = {};
        Cu.import(url, scope);
        return scope;
    }
    let {XPCOMUtils} = require("resource://gre/modules/XPCOMUtils.jsm");
    let {OS} = require("resource://gre/modules/osfile.jsm");
    
    return {
        classDescription: "iMacros Command line handler",
        classID: Components.ID("{5d5a54d9-729b-40a2-b876-3462a09eb4b8}"),
        contractID: "@iopus.com/cmdlinehandler;1",
        xpcom_categories: [{category: "command-line-handler", 
                            entry: "m-imacros-pipe-name"}],

        init() {
            let registrar = Components.manager
                .QueryInterface(Ci.nsIComponentRegistrar);
            registrar.registerFactory(
                this.classID, this.classDescription, this.contractID, this
            );

            let catMan = Cc["@mozilla.org/categorymanager;1"]
                .getService(Ci.nsICategoryManager);
            for(let cat of this.xpcom_categories)
                catMan.addCategoryEntry(
                    cat.category, (cat.entry || this.contractID),
                    this.contractID,
                    false, true
                );
        },

        terminate() {
            let catMan = Cc["@mozilla.org/categorymanager;1"]
                .getService(Ci.nsICategoryManager);
            for (let category of this.xpcom_categories)
                catMan.deleteCategoryEntry(
                    category, this.contractID, false
                );
            let registrar = Components.manager
                .QueryInterface(Ci.nsIComponentRegistrar);
            
            return Promise.resolve().then( 
                () => registrar.unregisterFactory(this.classID, this)
            );
        },

        
        createInstance(outer, iid) {
                if (outer)
                    throw Cr.NS_ERROR_NO_AGGREGATION;
                return this.QueryInterface(iid);
        },

        QueryInterface: XPCOMUtils.generateQI([Ci.nsICommandLineHandler,
                                               Ci.nsIFactory]),

        
        handle ( cl) {
            let pipe = cl.handleFlagWithParam("im-pipe", true);
            let {Si} = require("chrome://jsm/content/ScriptingInterface.js");
            if (pipe) {
                Si.initWithPipe(pipe);
            } else {
                
                
                let s = OS.Path.basename(OS.Constants.Path.profileDir);
                s = s.replace(/^\w+\./, ""); 
                Si.initWithPipe(s);
            }
            
            
        },

        helpInfo : " -im-pipe <pipe_name>  Set pipe for iMacros Scripting Interface\n",

    };
    
})();
